<?php
/**
 * (jobs)
 */
namespace App\Jobs\ProductStockup;

use App\Models\Product\ProductSku;
use App\Models\ProductStockup\Stockup;
use App\Models\SsBasic\StockupAreaClassifyEstimate;
use App\Models\SsBasic\StockupAreaSkuEstimate;
use App\Models\SsBasic\StockupAreaSkuRatio;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class StockupAreaSkuRatioJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $ratios;

    /**
     * AreaSkuRatioJob constructor.
     * @param $ratios
     */
    public function __construct($ratios)
    {
        $this->ratios = $ratios;
    }

    /**
     * Execute the job.
     * @return void
     */
    public function handle()
    {
        $this->exeFillData($this->ratios);
    }

    private function exeFillData($ratios){

        $keyData = [];
        foreach ($ratios as $ratio){
            list($areaId, $pskuId) = explode('_', $ratio->area_psku);
            $classifyId = ProductSku::getValueById($pskuId, 'classify_id');
            if (!$areaId || !$classifyId) continue;

            $temp_key = $areaId.'_'.$classifyId;
            if(!in_array($temp_key, $keyData)){
                $keyData[] = $temp_key;
            }
        }

        foreach ($keyData as $_key){
            list($areaId,$classifyId) = explode('_',$_key);

            //品类预估
            $areaClassifyEstimate = StockupAreaClassifyEstimate::query()
                ->where('classify_id',$classifyId)
                ->where('area_id',$areaId)
                ->first();
            if(!$areaClassifyEstimate) continue;

           //备货产品
            $stockups = Stockup::query()
                ->where('classify_id',$classifyId)
                ->where('area_id',$areaId)
                ->get();
            foreach ($stockups as $stockup){
                $apKey = $areaId.'_'.$stockup->psku_id;
                $ratio = StockupAreaSkuRatio::getSkuRatio($apKey);

                //sku预估
                $areaSkuEstimate = StockupAreaSkuEstimate::query()->firstOrNew(['area_psku' => $apKey]);
                for($i = 0; $i < StockupAreaSkuEstimate::NEW_ESTIMATE_NUM; $i++){
                    $estimateNum = intval(round($areaClassifyEstimate->{'estimate_num'.$i} * $ratio)) ?? 0;
                    $areaSkuEstimate->{'estimate_num'.$i} = $estimateNum;
                    $stockup->{'estimate_num'.$i} = $estimateNum;
                }
                $areaSkuEstimate->save();
                $stockup->save();
            }
        }
    }


}
